/**
 * 腾讯地图hook
 * emit 组件内的事件
 * params 初始化配置参数
 */
export default (emit?, params?) => {
  const store = reactive({
    latlng: [] as any[], //经纬度
    address: '', //地址
    zoom: 0, //缩放
    label: {} as any,
    addressInfo: {} as any,
    city: '',
  })
  if (params) Object.assign(store, params)

  const _window = window as any
  _window.QQmap = res => {
    _window['jsonp_callback']?.(res)
  }
  const mapKey = 'QEWBZ-WRF6V-ZH5PE-5ESLQ-33XU6-RKBEH'
  const map = ref<any>({})
  /**jsonp请求 */
  const jsonp = (url, callback) => {
    const callbackName = 'jsonp_callback'
    const script = document.createElement('script')
    script.src = url + '&callback=' + callbackName
    _window[callbackName] = data => {
      delete window[callbackName]
      document.body.removeChild(script)
      callback(data)
    }
    document.body.appendChild(script)
  }
  const locationService = (done?, title?, cb?) => {
    const location = store.latlng.join(',')
    console.log('🚀 ~ locationService ~ store:', store)
    console.log('🚀 ~ locationService ~ location:', location)
    jsonp('https://apis.map.qq.com/ws/geocoder/v1/?location=' + location + '&key=' + mapKey + '&output=jsonp&callback=?', res => {
      if (res.status == 0 && res.result) {
        store.addressInfo = res.result
        title
          ? ((store.addressInfo.address_component.street_number = title), (store.addressInfo.address = store.addressInfo.address_component.province + store.addressInfo.address_component.city + store.addressInfo.address_component.district + store.addressInfo.address_component.street + title))
          : ''
        let center = new _window.qq.maps.LatLng(...store.latlng)
        map.value.panTo(center)

        store.address = res.result.address
        store.city = res.result.address_component.city
        if (done == 'close') {
          cb?.()
          emit('setMap', {
            position: store.latlng,
            address: store.address,
            info: store.addressInfo,
          })
        }
      }
    })
  }
  const initcityService = (cb?) => {
    let cityService = new _window.qq.maps.CityService({
      complete: result => {
        map.value.setCenter(result.detail.latLng)
        store.city = result.detail.name
        store.latlng = [result.detail.latLng.lat, result.detail.latLng.lng]
        locationService(undefined, undefined, cb)
      },
    })
    cityService.searchLocalCity()
  }
  /**初始化地图*/
  const initMap = (mapContainer: HTMLElement, cb?) => {
    //设置Zoom
    map.value = new _window.qq.maps.Map(mapContainer, {
      zoom: store.zoom,
    })
    console.log('🚀 ~ initMap ~ map:', map)
    //创建Label
    map.value.label = new _window.qq.maps.Label({
      map: map.value,
      offset: new _window.qq.maps.Size(15, -12),
      draggable: false,
      clickable: false,
    })
    map.value.setOptions({
      draggableCursor: 'crosshair',
    })
    mapContainer.addEventListener('mouseenter', e => {
      map.value.label.setMap(map.value)
    })
    mapContainer.addEventListener('mouseleave', e => {
      map.value.label.setMap(null)
    })
    _window.qq.maps.event.addListener(map.value, 'mousemove', e => {
      var latlng = e.latLng
      map.value.label.setPosition(latlng)
      map.value.label.setContent(latlng.getLat().toFixed(6) + ',' + latlng.getLng().toFixed(6))
    })
    initcityService()
    cb?.()
    //点击获取地址
    _window.qq.maps.event.addListener(map.value, 'click', e => {
      jsonp('https://apis.map.qq.com/ws/geocoder/v1/?location=' + e.latLng.getLat() + ',' + e.latLng.getLng() + '&key=' + mapKey + '&output=jsonp&callback=?', res => {
        if (res.status == 0) {
          store.addressInfo = res.result
          store.address = res.result != undefined ? res.result.address : ''
          store.latlng = res.result != undefined ? [res.result.location.lat, res.result.location.lng] : []

          emit?.('setMap', {
            position: store.latlng,
            address: store.address,
            info: store.addressInfo,
          })
        }
      })
    })
  }

  return { initMap, mapKey, store, jsonp, map, locationService, _window }
}
